<template>
  <div class="app-container">
    <div class="main-container">
      <!-- 页面标题 -->
      <div class="page-header">
        <div class="header-left">
          <router-link to="/main/renshi/zhaoping/zhaopingxiudin" class="back-btn">
            <i class="el-icon-arrow-left"></i> 返回
          </router-link>
        </div>
        <div class="header-title">
          <i class="el-icon-document"></i>
          <span>{{ isView ? '查看' : (isEdit ? '编辑' : '新增') }}文件发放与回收记录</span>
        </div>
        <div class="header-actions">
          <el-button-group>
            <el-button type="primary" icon="el-icon-check" @click="handleSave" :loading="saving" v-if="!isView">
              保存
            </el-button>
            <el-button type="info" icon="el-icon-printer" @click="handlePrint">
              打印
            </el-button>
            <el-button type="primary" icon="el-icon-view" @click="goToList">
              列表
            </el-button>
          </el-button-group>
        </div>
      </div>

      <!-- 表单内容 -->
      <el-form
        ref="form"
        :model="formData"
        :rules="rules"
        label-width="120px"
        :disabled="isView"
        size="medium"
        class="form-container"
      >
        <el-card class="form-card" shadow="hover">
          <div class="form-title">基本信息</div>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="文件编号" prop="fileNumber">
                <el-input v-model="formData.fileNumber" placeholder="请输入文件编号" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="文件名称" prop="fileName">
                <el-input v-model="formData.fileName" placeholder="请输入文件名称" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <el-card class="form-card" shadow="hover">
          <div class="form-title">
            <span>发放与回收记录</span>
            <el-button
              type="text"
              icon="el-icon-plus"
              @click="addRecord"
              v-if="!isView"
            >
              添加记录
            </el-button>
          </div>

          <el-table
            :data="formData.records"
            border
            size="medium"
            style="width: 100%"
            :span-method="objectSpanMethod"
            :cell-style="cellStyle"
            :header-cell-style="headerCellStyle"
          >
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column label="版本" min-width="100">
              <template slot-scope="{row, $index}">
                <el-form-item
                  :prop="'records.' + $index + '.version'"
                  :rules="{ required: true, message: '版本不能为空', trigger: 'blur' }"
                >
                  <el-input v-model="row.version" placeholder="请输入版本" />
                </el-form-item>
              </template>
            </el-table-column>
            <!-- 发放部分 -->
            <el-table-column label="发放信息" align="center">
              <el-table-column label="份数" width="220px">
                <template slot-scope="{row, $index}">
                  <el-form-item
                    :prop="'records.' + $index + '.issueCopies'"
                    :rules="{ required: true, type: 'number', min: 0, message: '份数必须为非负数', trigger: 'blur' }"
                  >
                    <el-input-number
                      v-model="row.issueCopies"
                      :min="0"
                      controls-position="right"
                      placeholder="份数"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="分发号" min-width="120">
                <template slot-scope="{row, $index}">
                  <el-form-item :prop="'records.' + $index + '.distributionNumber'">
                    <el-input v-model="row.distributionNumber" placeholder="请输入分发号" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="部门" min-width="160">
                <template slot-scope="{row, $index}">
                  <el-form-item
                    :prop="'records.' + $index + '.issueDepartment'"
                    :rules="{ required: true, message: '发放部门不能为空', trigger: 'blur' }"
                  >
                    <el-input v-model="row.issueDepartment" placeholder="请输入发放部门" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="签收/日期" min-width="200">
                <template slot-scope="{row, $index}">
                  <el-form-item :prop="'records.' + $index + '.signAndDateIssue'">
                    <el-date-picker
                      v-model="row.signAndDateIssue"
                      type="datetime"
                      placeholder="请选择签收日期"
                      format="yyyy-MM-dd HH:mm"
                      value-format="yyyy-MM-dd HH:mm"
                      :picker-options="pickerOptions"
                      style="width: 100%"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
            </el-table-column>
            <!-- 回收部分 -->
            <el-table-column label="回收信息" align="center" class-name="recycle-section">
              <el-table-column label="份数" width="220px">
                <template slot-scope="{row, $index}">
                  <el-form-item
                    :prop="'records.' + $index + '.recycleCopies'"
                    :rules="{ type: 'number', min: 0, message: '份数必须为非负数', trigger: 'blur' }"
                  >
                    <el-input-number
                      v-model="row.recycleCopies"
                      :min="0"
                      controls-position="right"
                      placeholder="份数"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="部门" min-width="160">
                <template slot-scope="{row, $index}">
                  <el-form-item :prop="'records.' + $index + '.recycleDepartment'">
                    <el-input v-model="row.recycleDepartment" placeholder="请输入回收部门" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="签名/日期" min-width="200">
                <template slot-scope="{row, $index}">
                  <el-form-item :prop="'records.' + $index + '.signAndDateRecycle'">
                    <el-date-picker
                      v-model="row.signAndDateRecycle"
                      type="datetime"
                      placeholder="请选择回收日期"
                      format="yyyy-MM-dd HH:mm"
                      value-format="yyyy-MM-dd HH:mm"
                      :picker-options="pickerOptions"
                      style="width: 100%"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column label="备注" min-width="150">
              <template slot-scope="{row, $index}">
                <el-form-item :prop="'records.' + $index + '.remarks'">
                  <el-input v-model="row.remarks" placeholder="请输入备注" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              width="80"
              align="center"
              v-if="!isView"
            >
              <template slot-scope="{$index}">
                <el-button
                  type="text"
                  icon="el-icon-delete"
                  @click="removeRecord($index)"
                  class="delete-btn"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <div class="form-footer">
          表单编号及版本：AM - FR - 0006 A/0 生效日期：2006年11月1日 保存年限:长期
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import { getFileDistributionById, saveFileDistribution } from '@/api/fileDistribution'

export default {
  name: 'Ffhuishou',
  data() {
    return {
      isView: false,
      isEdit: false,
      saving: false,
      pickerOptions: {
        shortcuts: [
          {
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date())
            }
          },
          {
            text: '昨天',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          },
          {
            text: '一周前',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          }
        ],
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      },
      formData: {
        fileNumber: '',
        fileName: '',
        records: []
      },
      rules: {
        fileNumber: [
          { required: true, message: '请输入文件编号', trigger: 'blur' }
        ],
        fileName: [
          { required: true, message: '请输入文件名称', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    const { type, id } = this.$route.query
    this.isView = type === 'view'
    this.isEdit = type === 'edit'
    
    if (id) {
      this.getDetail(id)
    } else {
      this.addRecord()
    }
  },
  methods: {
    async getDetail(id) {
      try {
        const response = await getFileDistributionById(id)
        this.formData = response.data
      } catch (error) {
        console.error('获取详情失败:', error)
        this.$message.error('获取详情失败')
      }
    },
    addRecord() {
      this.formData.records.push({
        version: '',
        issueCopies: 0,
        distributionNumber: '',
        issueDepartment: '',
        signAndDateIssue: '',
        recycleCopies: 0,
        recycleDepartment: '',
        signAndDateRecycle: '',
        remarks: ''
      })
    },
    removeRecord(index) {
      this.formData.records.splice(index, 1)
    },
    async handleSave() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          this.saving = true
          try {
            await saveFileDistribution(this.formData)
            this.$message.success('保存成功')
            this.handleBack()
          } catch (error) {
            console.error('保存失败:', error)
            this.$message.error('保存失败')
          }
          this.saving = false
        }
      })
    },
    goToList() {
      this.$router.push('/main/biao/ffhuishouList')
    },
    handlePrint() {
      window.print()
    },
    handleBack() {
      this.$router.push('/main/biao/ffhuishouList')
    },
    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (column.className === 'issue-section' || column.parent?.className === 'issue-section') {
        return {
          backgroundColor: '#fafafa'
        }
      }
      return {}
    },
    headerCellStyle({ row, column, rowIndex, columnIndex }) {
      const style = {
        backgroundColor: '#f5f7fa',
        color: '#303133',
        fontWeight: '600'
      }
      
      if (column.className === 'issue-section' || column.parent?.className === 'issue-section') {
        style.backgroundColor = '#ecf5ff'
        style.color = '#409EFF'
      } else if (column.className === 'recycle-section' || column.parent?.className === 'recycle-section') {
        style.backgroundColor = '#f0f9eb'
        style.color = '#67c23a'
      }
      
      return style
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 24px;
  background-color: antiquewhite;
  min-height: calc(100vh - 48px);
}

.main-container {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  margin-bottom: 24px;
  padding: 20px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .header-title {
    display: flex;
    align-items: center;
    gap: 8px;
    
    i {
      font-size: 20px;
      color: #409EFF;
    }

    span {
      font-size: 18px;
      font-weight: 600;
      color: #303133;
    }
  }
}

.form-container {
  .form-card {
    margin-bottom: 24px;

    .form-title {
      font-size: 16px;
      font-weight: 500;
      color: #303133;
      margin-bottom: 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
}

.form-footer {
  text-align: center;
  color: #606266;
  margin-top: 24px;
  font-size: 14px;
}

:deep(.el-table) {
  .el-form-item {
    margin-bottom: 0;
  }

  .delete-btn {
    color: #F56C6C;
  }

  // 发放和回收信息的样式
  .issue-section {
    border-right: 2px solid #DCDFE6;
  }

  .recycle-section {
    border-left: 2px solid #DCDFE6;
  }

  .el-table__header {
    th {
      &.issue-section, &[class*="issue-section_"] {
        background-color: #ecf5ff !important;
        color: #409EFF !important;
      }

      &.recycle-section, &[class*="recycle-section_"] {
        background-color: #f0f9eb !important;
        color: #67c23a !important;
      }
    }
  }

  .el-table__body {
    td {
      &.issue-section, &[class*="issue-section_"] {
        background-color: #fafafa;
      }
    }
  }

  .el-date-editor.el-input {
    width: 100%;
  }
  
  .el-date-editor--datetime {
    width: 100% !important;
  }
}

@media print {
  .page-header {
    display: none;
  }

  .app-container {
    padding: 0;
    background-color: #fff;
  }

  .form-card {
    box-shadow: none !important;
    border: none !important;
  }
}
::v-deep .el-form-item {
  .el-form-item__content {
    margin-left: 0px !important;
  }
}
</style>